<?php

namespace app\wx\controller;

use app\common\library\Openssl;
use think\Db;
use think\facade\Request;
use think\Validate;
use think\helper\Time;

class Wxbind extends Base
{
    protected $beforeActionList = [
        'first',
    ];
    protected $openid = '';

    protected function first()
    {

        if (session('openid') || input('openid')) {
            if (!session('openid')) {
                $data['id'] = substr(config('cache.prefix'), 1);
                $openssl = new Openssl();
                $data['expires_in'] = time() + 60 * 10;
                $data['openid']=input('openid');
                $token = $openssl->encrypt(json_encode($data));
                $url = 'https://openwx.weibuyun.com/auth/subscribe?token=' . $token;
               $status= @file_get_contents($url);
                if($status!=1){
                    $url=url('/wx/interest/index' , '', '', Request::host());
                    $this->redirect($url);
                }
                session('openid', input('openid'));
            }
            $this->openid = session('openid');
        } else {
            $url = url('/wx/wxbind/index', 'token=' . input('token'), '', Request::host());
            $this->redirect('https://openwx.weibuyun.com/wxuser/get_openid' . '?domain=' . Request::host() . '&url=' . $url);
        }
    }

    public function index()
    {

        // dump($info);
        $openssl = new Openssl();
        $data = $openssl->decrypt(input('param.token'));
        $new_data = json_decode($data, true);
        $info = DB::name('admin')->where('id', $new_data['uid'])->find();
        if ($this->request->isPost() && input('?post.token')) {
            if ($new_data['expires_in'] < time()) {
                $this->error('TOKEN超时,请重样报扫码-30002');
            }
            $sdata['openid'] = session('openid');
            $sdata['last_login_time'] = time();
            if (DB::name('admin')->where('id', $new_data['uid'])->update($sdata)) {
                $this->success('微信绑定成功');
            } else {
                $this->error('微信绑定失败');
            }
        }

        if ($info) {
            if ($new_data['expires_in'] < time()) {
                $this->assign('info', 'TOKEN超时，请重样报扫码-30001');
                return view('work/error');
            }
            $info['face'] = "/wx" . trim($info['face']);
            //  dump($info);
            $this->assign('info', $info);
            $this->assign('token', input('token'));
            return view();
        } else {
            $this->assign('info', '没有找到你的用户信息');
            return view('work/error');
        }

    }


}
